#!/bin/env/python3
import datetime
import random
from datetime import timedelta

from flask import Flask, session, current_app
from info.models import User
from info import create_app, db, models  # 导入models 是让应用程序知道models的存在
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

# 调用方法获取app
app = create_app("develop")
manager = Manager(app)
Migrate(app, db)
manager.add_command('db', MigrateCommand)


# 给manager 添加脚本运行的方法
# 参数1 使用方法时传递的参数名称
# 参数2 对参数1的解释
# 参数3 目的参数，用来传递给形参用的
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def createsuperuser(username, password):
    # 创建用户对象
    # 设置用户属性
    admin = User()
    admin.nick_name = username
    admin.mobile = username
    admin.password = password
    admin.is_admin = True

    # 保存到数据库
    try:
        db.session.add(admin)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"
    return "创建成功"


# 为了图表好看 添加测试用户
@manager.option('-t', "--test", dest='test')
def add_test_user(test):
    # 定义容器
    user_list = []
    for i in range(1000):
        user = User()
        user.nick_name = "zhangtiantian%d" % i
        user.mobile = "139%08d" % i
        user.password_hash = "pbkdf2:sha256:150000$GLmz5ne7$4b4c936095c2c89c83b2b10ab9f7e764be34dd72806e1893394bebcacc88cf9d"
        # 设置登录时间为近30天
        user.last_login = datetime.datetime.now() - timedelta(seconds=random.randint(0, 30 * 24 * 3600))
        user_list.append(user)

    # 将用户添加到数据库中
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"
    return "创建成功"


if __name__ == '__main__':
    manager.run()
